<template>
  <div id="panel">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          :label-position="'right'"
        >
          <el-form-item label="水质类别分布" prop="type">
            <el-radio-group
              v-model="queryParams.type"
              size="medium"
              @change="tepeChange"
            >
              <el-radio-button label="按月"></el-radio-button>
              <el-radio-button label="按年"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            prop="riverid"
            v-if="queryParams.type == '按月'"
          >
            <el-date-picker
              v-model="times"
              :type="selectType"
              :value-format="dataValueType"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :key="selectType"
              @change="TimePicker"
              :clearable="false"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="riverid" v-else>
            <el-date-picker
              v-model="yeartype"
              value-format="yyyy"
              type="year"
              placeholder="选择开始年"
            >
            </el-date-picker>

            <el-date-picker
              v-model="yeartypeb"
              type="year"
              value-format="yyyy"
              placeholder="选择结束年"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="padding: 10px"
              >查询</el-button
            >
            <!-- <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              清除
            </el-button> -->
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="never">
          <div slot="header">
            <span>水质类别占比</span>
          </div>
          <div
            id="charOne"
            ref="charOne"
            style="height: 450px; width: 100%"
          ></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never">
          <div slot="header">
            <span>污染物超标次数统计</span>
          </div>
          <div
            id="charTwo"
            ref="charTwo"
            style="height: 450px; width: 100%"
          ></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import getTime from "@/utils/getTime.js";
import { updateDate, updateTime, updateTimeB } from "@/utils/ruoyi";
import dateUtil from "@/utils/dateUtil.js";
import {
  getWaterClassificationSg,
  getWaterClassificationMonthSg,
  getPollutantSg,
  getPollutantYearSg,
} from "@/api/waterBusiness/interface.js";
import { TimePicker } from "element-ui";
export default {
  name: "waterQuality",
  props: {
    dmid: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      timer: new Date().getTime(),
      queryParams: {
        type: "按月",
      },
      // 选择的类型
      selectType: "daterange",
      dataValueType: "yyyy-MM-dd",
      times: "",
      query: {
        id: this.dmid,
      },
      // 第一个echarts数据
      charDataa: {},
      // 第二个echarts数据
      charDatab: {},

      yeartype: new Date().getFullYear() - 1 + "",
      yeartypeb: new Date().getFullYear() + "",
    };
  },
  created() {
    this.tepeChange("按月");
    // const weekRange = dateUtil.getRecentWeek();
    // this.times = [weekRange.start, weekRange.end];
  },
  mounted() {
    // this.initChart();
    // this.init();
  },
  methods: {
    //获取最近一周的时间
    showWeekRange() {
      const weekRange = dateUtil.getRecentWeek();
      console.log("开始时间:", weekRange.start);
      console.log("结束时间:", weekRange.end);
    },
    // 获取最近三个月的时间
    showMonthRange() {
      const monthRange = dateUtil.getRecentMonth();
      console.log("开始时间:", monthRange.start);
      console.log("结束时间:", monthRange.end);
    },
    init() {
      this.getWaterClassificationSg();
      // this.getWaterClassificationMonthSg();
      this.getPollutantDay();
      // this.getPollutantYearSg();
    },
    // 处理数据格式，转换为ECharts需要的格式
    processData(resa) {
      return resa.map((item) => {
        // 每个对象只有一个键值对，获取键作为name，值作为value
        const name = Object.keys(item)[0];
        const value = Number(item[name]); // 转换为数字类型
        return { name, value };
      });
    },
    //水质分类分布（按日）
    getWaterClassificationSg() {
      getWaterClassificationSg(this.query).then((res) => {
        console.log("水质类别分布（按日）", res);
        if (res.code == 200) {
          this.charDataa = this.processData(res.data);
          console.log(">>>this.charDataa", this.charDataa);

          this.initChart();
        }
      });
    },
    //水质分类分布（按月）
    getWaterClassificationMonthSg() {
      getWaterClassificationMonthSg(this.query).then((res) => {
        console.log("水质类别分布（按月）", res);
        if (res.code == 200) {
          this.charDataa = this.processData(res.data);
          this.initChart();
        }
      });
    },
    //污染物超标次数统计（按日）
    getPollutantDay() {
      getPollutantSg(this.query).then((res) => {
        console.log("污染物超标次数统计（按日）", res);
        if (res.code == 200) {
          this.charDatab = res.data;
          this.initChart2();
        }
      });
    },
    // 污染物超标次数统计（按月）
    getPollutantYearSg() {
      getPollutantYearSg(this.query).then((res) => {
        if (res.code == 200) {
          this.charDatab = res.data;
          this.initChart2();
        }
      });
    },

    // 水质类别切换
    tepeChange(e) {
      this.times = [];
      console.log(">>>", e);
      // e == "按日"
      //   ? (this.selectType = "daterange")
      //   : (this.selectType = "monthrange");
      // e == "按日"
      //   ? (this.dataValueType = "yyyy-MM-dd")
      //   : (this.dataValueType = "yyyy-MM");
      if (e == "按月") {
        this.selectType = "monthrange";
        this.dataValueType = "yyyy-MM";
        const weekRange = dateUtil.getRecentWeek();
        const threeMonths = dateUtil.getRecentThreeMonths();
        this.times = [threeMonths.start, threeMonths.end];
        this.query.startTime = this.times[0];
        this.query.endTime = this.times[1];
        this.getWaterClassificationSg();
        this.getPollutantDay();
      } else {
        this.selectType = "monthrange";
        this.dataValueType = "yyyy";
        const threeMonths = dateUtil.getRecentThreeMonths();
        // this.times = [threeMonths.start, threeMonths.end];
        this.query.startTime = this.yeartype;
        this.query.endTime = this.yeartypeb;
        this.getWaterClassificationMonthSg();
        this.getPollutantYearSg();
      }
    },
    // 监听时间选择的变化
    TimePicker(val) {
      if (this.times) {
        this.query.startTime = this.times[0];
        this.query.endTime = this.times[1];
      }
    },
    //搜索
    handleQuery() {
      // this.init();
      if (this.queryParams.type == "按月") {
        this.tepeChange("按月");
      } else {
        this.tepeChange("按年");
      }
    },
    //重置、清除表单
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
    },
    // echarts图
    initChart() {
      let color = [
        "#0CD2E6",
        "#3751E6",
        "#FFC722",
        "#886EFF",
        "#008DEC",
        "#114C90",
        "#00BFA5",
      ];
      let legend = this.charDataa.map((item) => item.name);
      let seriesData = this.charDataa;
      let option = {
        color: color,
        title: {
          top: 20,
          textStyle: {
            fontSize: 20,
            color: "#DDEEFF",
          },
        },
        grid: {
          top: "15%",
          left: 0,
          right: "1%",
          bottom: 5,
          containLabel: true,
        },
        legend: {
          orient: "vertical",
          top: "center",
          right: 50,
          textStyle: {
            align: "left",
            verticalAlign: "middle",
            rich: {
              name: {
                color: "rgba(0,0,0,0.5)",
                fontSize: 14,
              },
              value: {
                color: "rgba(0,0,0,0.5)",
                fontSize: 14,
              },
              rate: {
                color: "rgba(0,0,0,0.9)",
                fontSize: 14,
              },
            },
          },
          data: legend,
          formatter: (name) => {
            if (seriesData.length) {
              const item = seriesData.filter((item) => item.name === name)[0];
              return `{name|${name}：}{value| ${item.value}} {rate| ${item.value}%}`;
            }
          },
        },
        series: [
          {
            name: "需求类型占比",
            type: "pie",
            center: ["35%", "50%"],
            radius: ["45%", "65%"],
            label: {
              normal: {
                show: false,
                position: "center",
                formatter: "{value|{c}}\n{label|{b}}",
                rich: {
                  value: {
                    padding: 5,
                    align: "center",
                    verticalAlign: "middle",
                    fontSize: 32,
                  },
                  label: {
                    align: "center",
                    verticalAlign: "middle",
                    fontSize: 16,
                  },
                },
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: "12",
                },
              },
            },
            labelLine: {
              show: false,
              length: 0,
              length2: 0,
            },
            data: seriesData,
          },
        ],
      };
      // let maChar = echarts.init(document.getElementById("waterQuality"));
      let maChar = echarts.init(this.$refs.charOne);
      maChar.setOption(option);
      window.addEventListener("resize", function () {
        maChar.resize();
      });
    },
    // 右侧echarts
    initChart2() {
      const series = [];
      const dataKeys = Object.keys(this.charDatab);

      dataKeys.forEach((key) => {
        if (key !== "dateList") {
          // 跳过x轴数据
          series.push({
            name: key, // 系列名称（如“电导率”）
            type: "bar", // 柱状图类型
            data: this.charDatab[key].map((item) => Number(item)), // 转换为数字类型
            barWidth: 15, // 柱子宽度
            itemStyle: {
              borderRadius: 4, // 柱子圆角
            },
          });
        }
      });
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          data: series.map((item) => item.name), // 图例数据（所有监测指标）
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.charDatab.dateList, // x轴为日期
            axisLabel: {
              rotate: 30, // 日期文字旋转30度，避免重叠
              // interval: 0, // 强制显示所有标签
            },
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: series, // 系列数据
      };
      // let maChar = echarts.init(document.getElementById("waterQuality"));
      let maChar = echarts.init(this.$refs.charTwo);
      maChar.setOption(option);
      window.addEventListener("resize", function () {
        maChar.resize();
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
